package com.jianshuge.app.common;


import com.jianshuge.app.AppConfig;
import com.jianshuge.app.AppContext;
import com.jianshuge.app.AppException;
import com.jianshuge.app.R;
import com.jianshuge.app.api.ApiClient;
import com.jianshuge.app.bean.MyResult;
import com.jianshuge.app.bean.User;

import com.jianshuge.app.ui.Main;
import com.jianshuge.app.ui.Setting;
import com.jianshuge.oauth.AccessToken;
import com.jianshuge.oauth.Douban;
import com.jianshuge.oauth.OAuthDialogError;
import com.jianshuge.oauth.OAuthDialogListener;
import com.jianshuge.oauth.OAuthException;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Toast;

/**
 * 豆瓣帮助类
 */
public class DoubanHelper {

	private static final String CONSUMER_KEY = "037090f5389b9f810a51b2dfa9d2de83";
	private static final String CONSUMER_SECRET = "491ee819068f282b";
	private static final String REDIRECT_URL = "http://www.jianshuge.com/doubanlogin";
	
	public static final int OAUTH_ERROR = 0;
	public static final int OAUTH_RequestToken_ACCESS = 1;
	public static final int OAUTH_RequestToken_ERROR = 2;
	public static final int OAUTH_AccessToken_ACCESS = 3;
	public static final int OAUTH_AccessToken_ERROR = 4;
	public static final int OAUTH_AccessToken_SXPIRED = 5;
	
	private static Douban 			douban = null;
	private static AccessToken		accessToken = null;
	private static String			shareMessage = null;
	private static Activity			context = null;
	public static ProgressDialog	progressDialog = null;
	
	
	public static void setAccessToken(String accessKey,String accessSecret,long expiresIn){
		accessToken = new AccessToken(accessKey, accessSecret);
		accessToken.setExpiresIn(expiresIn);
	}
	
	public static Handler  handler	= new Handler(){ 
		
		public void handleMessage(Message msg) { 
			if(progressDialog != null)
				progressDialog.dismiss();
		    switch (msg.what) 
		    { 
		    	case OAUTH_ERROR: 
		    		Toast.makeText(context, context.getString(R.string.OAUTH_ERROR), Toast.LENGTH_SHORT).show();
		    		break; 
		    	case OAUTH_RequestToken_ACCESS:
		    		Toast.makeText(context, context.getString(R.string.OAUTH_RequestToken_ACCESS), Toast.LENGTH_SHORT).show();
		    		break;
		    	case OAUTH_RequestToken_ERROR: 
		    		Toast.makeText(context, context.getString(R.string.OAUTH_RequestToken_ERROR), Toast.LENGTH_SHORT).show();
		    		break; 
		    	case OAUTH_AccessToken_ACCESS:
		    		Toast.makeText(context, context.getString(R.string.OAUTH_AccessToken_ACCESS), Toast.LENGTH_SHORT).show();
		    		break;
		    	case OAUTH_AccessToken_ERROR: 
		    		Toast.makeText(context, context.getString(R.string.OAUTH_AccessToken_ERROR), Toast.LENGTH_SHORT).show();
		    		authorize(context, shareMessage);//跳转到授权页面
		    		break;
		    	case OAUTH_AccessToken_SXPIRED: 
		    		Toast.makeText(context, context.getString(R.string.OAUTH_AccessToken_SXPIRED), Toast.LENGTH_SHORT).show();
		    		authorize(context, shareMessage);//跳转到授权页面
		    		break;
		    }
		    UIHelper.redirectTo(context);
		};
	};
	
	/**
	 * 判断weibo是否为null
	 * @return
	 */
	public static boolean isDoubanNull()
	{
		if(douban == null)
			return true;
		else 
			return false;
	}
	/**
	 * 初始化douban
	 */
	public static void initDouban()
	{
		douban = Douban.getInstance();
		douban.setupConsumerConfig(CONSUMER_KEY, CONSUMER_SECRET);
		douban.setRedirectUrl(REDIRECT_URL);
	}

	/**
	 * 豆瓣认证授权
	 */
	public static void authorize( final Activity cont, final String shareMsg )
	{		
		context = cont;
		
		if(isDoubanNull())
		{
			initDouban();
		}
		
		douban.authorize(cont, new OAuthDialogListener() {

			public void onComplete(Bundle values) {
	    		try 
	    		{	
					String token = values.getString(Douban.ACCESS_TOKEN);
					String expires_in = values.getString(Douban.EXPIRES_IN );
					accessToken = new AccessToken(token, CONSUMER_SECRET);
					accessToken.setExpiresIn(expires_in);	
					//保存AccessToken
					AppConfig.getAppConfig(cont).setAccessInfo(accessToken.getToken(), accessToken.getSecret(), accessToken.getExpiresIn(), "douban");
					//登陆荐书阁
					String login_uid = values.getString("douban_user_id");		        
					login(cont, token, "douban");
	    		} 
	    		catch (Exception e) 
	    		{
	    			e.printStackTrace();
	    		}
			}
	    	
			@Override
			public void onError(OAuthDialogError e) {
				Toast.makeText(context,"授权失败 : " + e.getMessage(), Toast.LENGTH_LONG).show();
			}
			@Override
			public void onCancel() {
				//Toast.makeText(context, "取消授权", Toast.LENGTH_LONG).show();
			}
			@Override
			public void onAuthException(OAuthException e) {
				Toast.makeText(context,"授权异常 : " + e.getMessage(), Toast.LENGTH_LONG).show();
			}
		});		
	}

	/**
	 * 登陆荐书阁
     * Toast会提示登陆成功或失败
	 */
    public static void loginJianshuge(Activity cont, String login_uid)
    {	
    	context = cont;      	
    	if(isDoubanNull())
		{
			initDouban();
		}
		
    	Message msg = new Message();
     	
    	//判断是否授权
    	if(accessToken == null)
    	{
    		msg.what = OAUTH_AccessToken_ERROR;
    		handler.sendMessage(msg);
    		return;
    	}
    	
    	//判断token是否过期
    	if(accessToken.getExpiresIn() < System.currentTimeMillis())
    	{
    		msg.what = OAUTH_AccessToken_SXPIRED;
    		handler.sendMessage(msg);
    		return;
    	}
    	
    	msg.what = OAUTH_AccessToken_ACCESS;
        handler.sendMessage(msg);
	}
    
    //登录验证
    public static void login(Activity cont, final String access_token, final String login_type) {
    	
    	if( context == null)
    		context = cont; 
    	
		final Handler handler = new Handler() {
			public void handleMessage(Message msg) {
				if(msg.what == 1){
					User user = (User)msg.obj;
					if(user != null){
						
						//清空原先cookie
						ApiClient.cleanCookie();
						//发送通知广播
						//UIHelper.sendBroadCast(context, user.getNotice());
						//提示登陆成功
						UIHelper.ToastMessage(context, R.string.msg_login_success);
						
						//跳转--加载用户动态
						Intent intent = new Intent(context, Main.class);
						intent.putExtra("LOGIN", true);
						context.startActivity(intent);
						context.finish();
					}
				}else if(msg.what == 0){
					UIHelper.ToastMessage(context, context.getString(R.string.msg_login_fail)+msg.obj);
				}else if(msg.what == -1){
					((AppException)msg.obj).makeToast(context);
				}
			}
		};
		
		new Thread(){
		
			public void run() {
				Message msg =new Message();
				try {
					AppContext ac = (AppContext)context.getApplication(); 
					
	                User user = ac.login_auth(access_token, login_type);
                 	
	                MyResult res = user.getValidate();
	                if(res.OK()){
	                	ac.saveLoginInfo(user);//保存登录信息
	                	msg.what = 1;//成功
	                	msg.obj = user;
	                }else{
	                	ac.cleanLoginInfo();//清除登录信息
	                	msg.what = 0;//失败
	                	msg.obj = res.getErrorMessage();
	                }
	                
	            } catch (AppException e) {
	            	e.printStackTrace();
			    	msg.what = -1;
			    	msg.obj = e;
	            }
				handler.sendMessage(msg);
			}
		}.start();
    }   
}